package com.hnust.service.impl;

import com.hnust.api.ChapterApi;
import com.hnust.controller.personInfo.ChapterImportController;
import com.hnust.domain.ChapterData;
import com.hnust.domain.ChapterDataRecord;
import com.hnust.fx.DialogBuilder;
import com.hnust.service.ChapterServices;
import com.hnust.util.FileUpload;
import com.jfoenix.controls.JFXButton;
import io.datafx.core.concurrent.ProcessChain;
import javafx.collections.ObservableList;
import javafx.scene.control.TableView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.DirectoryChooser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * @Author: Yjx
 * @Data: 2021/10/27 17:46
 * @Version 1.0
 * @Project_Name: testTeacher
 * @describe
 */
@Service("chapterServices")
public class ChapterServicesImpl implements ChapterServices {
    @Autowired
    ChapterApi chapterApi;

    @Override
    public void downloadFile(JFXButton downloadBtn) {
        ProcessChain.create().addRunnableInPlatformThread(() -> {
                    downloadBtn.setText("下载中...");
                    downloadBtn.setDisable(true);
                }).addSupplierInExecutor(() -> chapterApi.getTem())
                .addConsumerInPlatformThread((response) -> {
                    InputStream in = null;
                    FileOutputStream os = null;
                    try {
                        in = response.body().asInputStream();
                        DirectoryChooser directoryChooser = new DirectoryChooser();
                        File file1 = directoryChooser.showDialog(null);
                        String path = file1.getPath();//选择的文件夹路径
                        os = new FileOutputStream(path + "\\" + "批量课程章节模板.docx");
                        byte[] buffer = new byte[4 * 1024];
                        int read;
                        while ((read = in.read(buffer)) > 0) {
                            os.write(buffer, 0, read);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                        new DialogBuilder(downloadBtn).setTitle("提示").setMessage("下载文件失败，请稍后再试").
                                setPositiveBtn("确定", "#ff3333").create();
                    } finally {
                        try{
                            if (os != null) {
                                os.close();
                            }
                            if (in != null) {
                                in.close();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            new DialogBuilder(downloadBtn).setTitle("提示").setMessage("下载文件失败，请稍后再试").
                                    setPositiveBtn("确定", "#ff3333").create();
                        }
                    }
                }).withFinal(() -> {
                    downloadBtn.setText("下载Word文档");
                    downloadBtn.setDisable(false);
                }).run();
    }

    @Override
    public void allImport(ChapterDataRecord list,String courseId, JFXButton allImportBut,ObservableList<ChapterImportController.ChapterList> data, HBox form) {
        ProcessChain.create().addRunnableInPlatformThread(() -> {

        }).addSupplierInExecutor(() -> chapterApi.allImport(list,courseId)).addConsumerInPlatformThread((result -> {
                new DialogBuilder(allImportBut).setTitle("提示").setMessage(result.getMsg()).
                        setPositiveBtn("确定", "#ff3333").create();
                data.clear();
                form.setVisible(false);

        })).onException(e -> {
            e.printStackTrace();
            new DialogBuilder(allImportBut).setTitle("提示").setMessage("无法连接到服务器，请检查网络").
                    setPositiveBtn("确定", "#ff3333").create();
        }).withFinal(() -> {

        }).run();
    }

    @Override
    public void uploadFile(File file, JFXButton uploadBtn, String selectCourseId, ObservableList<ChapterImportController.ChapterList> data, TableView<ChapterImportController.ChapterList> TableView, HBox form, VBox loadingUploadInfo) {
        ProcessChain.create().addRunnableInPlatformThread(() -> {
            data.clear();
            uploadBtn.setText("上传文档中...");
            uploadBtn.setDisable(true);
            form.setManaged(false);
            form.setVisible(false);
            loadingUploadInfo.setVisible(true);
            loadingUploadInfo.setManaged(true);
        }).addSupplierInExecutor(() -> chapterApi.upload(FileUpload.fileToMultipartFile(file),selectCourseId)).addConsumerInPlatformThread((result -> {
            if (result.getCode() == 1) {
                List<ChapterData> ChapterData= result.getData();
                ChapterData.forEach(chapterData -> {data.add(new ChapterImportController.ChapterList(chapterData.getName(),chapterData.getChapter(),chapterData.getFrist(),chapterData.getSecond(),chapterData.getThird()));});
                TableView.setItems(data);
                loadingUploadInfo.setVisible(false);
                loadingUploadInfo.setManaged(false);
                form.setManaged(true);
                form.setVisible(true);
            } else {
                new DialogBuilder(uploadBtn).setTitle("提示").setMessage(result.getMsg()).
                        setPositiveBtn("确定", "#ff3333").create();
            }
        })).onException(e -> {
            e.printStackTrace();
            new DialogBuilder(uploadBtn).setTitle("提示").setMessage("无法连接到服务器，请检查网络").
                    setPositiveBtn("确定", "#ff3333").create();
        }).withFinal(() -> {
            uploadBtn.setText("上传文档");
            uploadBtn.setDisable(false);
            loadingUploadInfo.setVisible(false);
            loadingUploadInfo.setManaged(false);
        }).run();
    }
}
